function Validator()
{
    this.IsString=function (value)
    {
        var reg = /[\w]/g;
        return reg.test(value);
    };   
   
    this.IsInt=function (value)
    {
        var reg = /^\s*[-\+]?\d+\s*$/;
        return reg.test(value);
    };
   
    this.IsNumber=function (value)
    {
        var reg = /^\s*?\d+\s*$/;
        return reg.test(value);
    };
   
    this.IsFloat=function (value)
    {
        var reg = /^[-]{0,1}[0-9]{0,10}[.]{0,1}[0-9]{0,4}$/;
        return reg.test(value);
    };
   
    this.IsEmail=function (value)
    {
        var reg = /^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/;
        return reg.test(value);
    };
   
    this.IsDate=function (value)
    {
        var reg =  /^[1-2]{1,1}[0-9]{3,3}[-]{1,1}[0-9]{1,2}[-]{1,1}[0-9]{1,2}$/;
        return reg.test(value);
    };   
}





function AddFormValidator(formName)
{
  	 var form=$get(formName);
	 if (!form) return false;
	 if ((!form.onsubmit)&&(form.onsubmit!=""))
	 { 		
		$addHandler(form,"submit",Function.createDelegate(form,Form_OnSubmit));
	 }
	
	for (var i=0;i<form.elements.length;i++)
	  {        
	        var element=form.elements[i];	
	        if (element.getAttribute("required")=="true")
	        {
	        	addRequiredStyle(element);
	        }
	        element.setAttribute("oldClass",element.className);
	        if ((element.type!='sumbmit')&&(element.type!='button')&&(element.type!='reset'))
	        {
		        $addHandler(element,"keydown",Function.createDelegate(element,Element_OnKeyDown));
		        $addHandler(element,"keypress",Function.createDelegate(element,Element_OnKeyPress));
		        $addHandler(element,"beforepaste",Function.createDelegate(element,Element_OnKeyDown));
		        $addHandler(element,"focus",Function.createDelegate(element,Element_OnFocus));
		        $addHandler(element,"blur",Function.createDelegate(element,Element_OnBlur));
	        }
	  }
	
}

function addRequiredStyle(element)
{	 
	 if ((!element.readonly)&&(!element.disabled)&&(element.clientHeight>0)&&(!element.getAttribute("RequiredHidden")))
	 {
		 element.className="TextBoxRequired";
		 element.oldClass="TextBoxRequired";
		 return;		
		 var requiredLayer=document.createElement("div");
		 requiredLayer.className="RequiredLayer";
		 requiredLayer.style.left=$getLeft(element)+element.clientWidth+3+"px";
		 requiredLayer.style.top=$getTop(element)+(element.offsetHeight/4)+"px";
		 requiredLayer.innerHTML="*";	
		 document.body.appendChild(requiredLayer);
	 }
	
	 
}

function Element_OnFocus(event)
{		      
		   if (this.className=="TextBox")
		   {
			   this.className="TextBoxFocus";
		   }
}

function Element_OnBlur(event)
{
   if (!$checkLength(this))
   {
      showValidatorMessage(this);
      return false;
   }  
   this.className=this.getAttribute("oldClass");    
}

function $checkLength(element)
{
    var isViald=true;
   var minLength=(element.getAttribute("minLength")?element.getAttribute("minLength"):element.getAttribute("minlength"));
   var maxLength=(element.getAttribute("maxLength")?element.getAttribute("maxLength"):element.getAttribute("maxlength")); 
   if (!element.value) return true;
   var value=element.value.trim();
   if (minLength)
   {
      if (value.getBytes()<parseInt(minLength))
      {
         isViald=false;
      }
   }
   if (maxLength)
   {
      if (value.getBytes()>parseInt(maxLength))
      {
         isViald=false;
      }
   } 
   return isViald;
   
}

function showValidatorMessage(element)
{  
       var errMessage=element.getAttribute("errMessage");
       if (errMessage)
       {    
    	   if ((!element.readonly)&&(!element.disabled)&&(element.clientHeight>0))
		   {
		           element.focus();
		   }
    	   element.style.width=element.offsetWidth+"px";
   	       element.className=element.getAttribute("oldClass")+"Error";    	   
   	       element.title=errMessage;    	
       }        	
      
}




function Element_OnKeyPress(event)
{   
	var dataType=this.getAttribute("dataType");	 	
	if (dataType)
	{
		switch(dataType.toLocaleLowerCase())
		{
		   case "+int":
			if (!((event.keyCode>=48)&&(event.keyCode<=57))&&(event.keyCode!=13)&&(event.keyCode!=46))			
			{
				event.returnValue=false;
			}				
			break;
			case "int":	
				if (!((event.keyCode>=48)&&(event.keyCode<=57))&&(event.keyCode!=13))			
				{
					event.returnValue=false;
				}				
				break;
		    case "+double":	
			case "+float":			
				if (!((event.keyCode>=48)&&(event.keyCode<=57))&&(event.keyCode!=13)&&(event.keyCode!=46))
				{
					event.returnValue=false;				
				}				
				break;	
		    case "double":	
			case "float":			
				if (!((event.keyCode>=48)&&(event.keyCode<=57))&&(event.keyCode!=13)&&(event.keyCode!=46)&&(event.keyCode!=45))
				{
					event.returnValue=false;				
				}				
				break;	
			case "datffe":				
				if(((this.value.length==4)&&(event.keyCode==110))||((this.value.length==6)&&(event.keyCode==110))||(event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)||(event.keyCode==8)||(event.keyCode==46)||(event.keyCode==37)||(event.keyCode==39))
				{
					event.returnValue=false;				
				}				
				break;	
		}	
	}	
}


function Element_OnKeyDown(event)
{		
	if ((this.value=="")&&(this.getAttribute("required")=="true")&&(event.keyCode==13))
    {	
		event.cancelBubble = true;
		event.returnValue=false;		
    }	 
	var dataType=this.getAttribute("dataType");
	if (dataType)
	{  
		dataType=dataType.toLocaleLowerCase();		
		if((dataType=="int")||(dataType=="numbar")||(dataType=="float")||(dataType=="double"))
		{ 
		    event.returnValue=false;
		  
			if ((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)||(event.keyCode==229)||(event.keyCode==110)||((this.value==""&&event.keyCode==189))||(event.keyCode==190)||(event.keyCode==37)||(event.keyCode==39)||(event.keyCode==46)||(event.keyCode==8)||(event.keyCode==198))
			{
				event.returnValue=true;				
			}
		}
		else if(dataType=="ascii")
		{
		   event.returnValue=false;		 
		   if ((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)||(event.keyCode==229)||(event.keyCode>=65&&event.keyCode<=90)||(event.keyCode==37)||(event.keyCode==39)||(event.keyCode==46)||(event.keyCode==8))
		  {
				event.returnValue=true;				
		   }
		}
		
	}
	
}
function Form_OnSubmit()
{
   return Form_Submit(this); 	
}

function Form_Submit(formName)
{  
	var form=$get(formName);	
	
    for (var e=0;e<form.elements.length;e++)
    {
        var isViald=true;
        var element=form.elements[e];
        if (element.value==undefined) continue;
        if ((element.value.trim()=="")&&(element.getAttribute("required")=="true"))
        {        	
            isViald=false;
        }
        else if (element.value!="")
        {
	        var expression=null;	       
	        var dataType=element.getAttribute("dataType");	  	     
	        if (dataType)
	        {	        	
		        switch(dataType.toLocaleLowerCase())
		        {
		        	case "string":
		        		expression = /[\w]/g;
		        		isViald=expression.test(element.value);
		        		break;
		        	case "int":
		        		expression=/^\s*[-\+]?\d+\s*$/;	
		        		isViald=expression.test(element.value);		        	  		
		        		break;
		        	case "+int":
		        		expression=/^\s*[+]?\d+\s*$/;	
		        		isViald=expression.test(element.value);		        	  		
		        		break;
		        	case "float":
		        		expression = /^[-]{0,1}[0-9]{0,10}[.]{0,1}[0-9]{0,4}$/;		        		
		        		isViald=expression.test(element.value);
		        		break;
		        	case "+float":
		        		expression = /^[0-9]{0,10}[.]{0,1}[0-9]{0,4}$/;		        		
		        		isViald=expression.test(element.value);
		        		break;
		        	case "date":
		        		expression=new RegExp("^\\s*((\\d{4})|(\\d{2}))([-/]|\\. ?)(\\d{1,2})\\4(\\d{1,2})\\s*$");
		        		isViald=expression.test(element.value);
		        		break;
		        	case "url":
		        		expression=new RegExp("/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[/\w\-.\/?%&=]*)?/");
		        		isViald=expression.test(element.value);
		        		break;
		        	case "email":              
		        	// /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
		        		//expression=new RegExp("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/");
		        		expression=/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;	
		        		isViald=expression.test(element.value);
		        		break;
		        	case "phone":
		        		expression=/^(((\d{3,4}-)?\d{7,8})|(1\d{10}))$/;	
		        		isViald=expression.test(element.value.trim());
		        		break;
		        	case "ic":
		        	case "idcard":
			        	var provinces={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
						            21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
						            33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
						            42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
						            51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
						            63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"
						           };
		        		expression=/(^\d{15}$)|(^\d{17}(\d|X)$)/;
		        		isViald=expression.test(element.value);
		        		if (isViald)
		        		{
		        		   isViald=(provinces[element.value.substr(0,2)]?true:false);
		        		}
		        		break;
		        	case "ascii":
		        	    expression=new RegExp("^[A-Za-z0-9]+$");		        	  
		        		isViald=expression.test(element.value);
		        	    break;
		        	case "post":
		        		expression=/^[1-9]\d{5}$/;
		        		isViald=expression.test(element.value);
		        		break;
		        	case "javascript":		        		
		        		var script=element.getAttribute("script");
		        		isViald=eval(script+"(element)");
		        		break;
		        	case "expression":
		     	        expression=new RegExp(element.getAttribute("expression"));
		     	        isViald = expression.test(element.value);
		            default:
		               try
		               {
		                 eval(dataType+"(element)");
		               }
		               catch(ex)
		               {		                 
		               };
		               break;
		        }
	        }	        
        }        
        if (!$checkLength(element))
        {
           isViald=false;
        }   
          	         
        if (!isViald)
        { 
           showValidatorMessage(element);
           return false;
        }
    }
    return true;
}

function EmptyToFocus(sender)
{
	var index=sender.getAttribute("position")?sender.getAttribute("position"):0;
	var element=sender.parentNode.getElementsByTagName("input")[index];
	if (element.value=="")
	{
		showValidatorMessage(element);
		return false;
	}
	return true;
}

function Page_OnLoadValidator()
{
	for (var f = 0; f < document.forms.length;f++)
	{
		 var form = document.forms[f];		 
		 AddFormValidator(form);
	}
}

$addHandler(window,"load",Page_OnLoadValidator);


function GetFormParamter(formName)
{
    var element;
    var name;
    var form = $get(formName);
    var param = new StringBuilder();


    var elements = form.getElementsByTagName("input");
    var length = elements.length;


    for (var i = 0; i < length; i++)
    {
        element = elements[i];
        name = element.name;
        if (typeof (name) === "undefined" || (name === null) || (name.length === 0) || element.disabled)
        {
            continue;
        }
        var type = element.type;
        if ((type === 'text') || (type === 'password') || (type === 'hidden') || (((type === 'checkbox') || (type === 'radio')) && element.checked))
        {
            param.append(encodeURIComponent(name));
            param.append("=");
            param.append(encodeURIComponent(element.value));
            param.append("&");
        }

    }
    elements = form.getElementsByTagName("textarea");
    length = elements.length;
    for (var i = 0; i < length; i++)
    {
        element = elements[i];
        name = element.name;
        if (typeof (name) === "undefined" || (name === null) || (name.length === 0) || element.disabled)
        {
            continue;
        }

        param.append(encodeURIComponent(name));
        param.append("=");
        param.append(encodeURIComponent(element.value));
        param.append("&");

    }
    elements = form.getElementsByTagName("select");
    length = elements.length;
    for (var i = 0; i < length; i++)
    {
        element = elements[i];
        name = element.name;
        var isFind = false;
        for (var j = 0; j < form.length; j++)
        {
            if (form.elements[j].name == name)
            {
                isFind = true;
                break;
            }
        }
        if (!isFind)
        {
            alert(name);
        }
        if (typeof (name) === "undefined" || (name === null) || (name.length === 0) || element.disabled)
        {
            continue;
        }
        var optionCount = element.options.length;
        for (var j = 0; j < optionCount; j++)
        {
            var option = element.options[j];
            if (option.selected)
            {
                param.append(encodeURIComponent(name));
                param.append("=");
                param.append(encodeURIComponent(option.value));
                param.append("&");
            }
        }
    }
    return param.toString();
}

function Form_SendForm(formName,onSuccess,onError)
{
	
    if (!Form_Submit(formName)) return false;
   
	var form = $get(formName);
	var param=GetFormParamter(form);
	
	if (form.getAttribute("onStart"))
	{
		eval(form.getAttribute("onStart"));
	}
	var isShowLoading=true;
	if (form.getAttribute("isShowLoading"))
	{
		isShowLoading=form.getAttribute("isShowLoading");
	}
	
	var request = new $WebRequest(form.action, param, onSuccess,onError,isShowLoading,form.getAttribute("loadingHandleId"),eval(form.getAttribute("onShowLoading")),eval(form.getAttribute("onHideLoading")));
	request.Start();
	return false;
}

function Form_AjaxSubmit(formName)
{
    var form = $get(formName);
	return Form_SendForm(formName,eval(form.getAttribute("onSuccess")),eval(form.getAttribute("onError")));
};

function Form_JsonSubmit(formName)
{	  
	
    var form = $get(formName);  
    return Form_SendForm(formName,function (result){getJsonResult(result,eval(form.getAttribute("onSuccess")),eval(form.getAttribute("onError")))});	
};
function Form_JsonSubmitNoValidat(formName){

    var form = $get(formName);
    return Form_SendFormNoValidat(formName,function (result){getJsonResult(result,eval(form.getAttribute("onSuccess")),eval(form.getAttribute("onError")))});
};
 function Form_SendFormNoValidat(formName,onSuccess,onError)
{
	var form = $get(formName);
	var param=GetFormParamter(form);

	if (form.getAttribute("onStart"))
	{
		eval(form.getAttribute("onStart"));
	}
	var isShowLoading=true;
	if (form.getAttribute("isShowLoading"))
	{
		isShowLoading=form.getAttribute("isShowLoading");
	}

	var request = new $WebRequest(form.action, param, onSuccess,onError,isShowLoading,form.getAttribute("loadingHandleId"),eval(form.getAttribute("onShowLoading")),eval(form.getAttribute("onHideLoading")));
	request.Start();
	return false;
}
function getJsonResult(result,onSuccess,onError)
{   
       if (result.code)
	   {   
		   switch (result.code)
		   {
		        case 0:  
		        case 1:         
		          onSuccess(result);		          
		          break;
		        case -1:		        	
		        case -2:		        
		          var msg = result.msg;
		          msg += '<br><a href="javascript:;" onclick="if(_err_msg_90009.style.display==\'\'){_err_msg_90009.style.display=\'none\';}else {_err_msg_90009.style.display=\'\';}">详细信息</a>'
		          msg += '<div id="_err_msg_90009" style="display:none;text-align: left;overflow:auto;">' + result.expMsg + '</div>';
		          Dialog.Alert("错误提示",msg,function (){if (onError){onError(result)}},380,200);
		          break;  
		        case -3:
		          //Dialog.Alert("超时提示",result.msg.mx,function (){top.location.href=baseUrl+'/'},500,90);	
		          Dialog.Alert("超时提示",result.msg.mx,function (){top._relogin()},500,90);	
		          break;		         
		   }
	   }
	   else
	   {		   
	      if (onSuccess)
	      {  
	         onSuccess(result);
	      }
	   }	
}